import json
from datetime import datetime, timedelta
import jwt
from django.shortcuts import render
from django.http import JsonResponse, HttpResponseRedirect
from rest_framework.views import APIView
from rest_framework.response import Response

from medical import settings
from .models import *
from .serilizers import *
from django.core.paginator import Paginator
from medical.settings import SECRET_KEY
import redis

# Create your views here.

"""class TestView(APIView):
    def get(self,request):
        roles = TestRole.objects.all()
        ser = TestRoleSer(roles,many=True)
       
        return Response({"code":200,'mes':ser.data})
    def post(self,request):
        ser = TestRoleSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200,'mes':'添加成功'})
        else:
            print(ser.errors)
            return Response({"code":200,'mes':ser.errors})"""


class ResourceView(APIView):
    def post(self, request):
        data = request.data
        ser = ResourceSer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, 'mes': '添加成功'})
        else:
            print(ser.errors)
            return Response({"code": 200, 'mes': ser.errors})

    def get(self, request):
        try:
            data = Resource.objects.all()
            ser = ResourceSer(data, many=True)
        except Exception as e:
            print(e)
            return Response({"code": 200, 'mes': '获取失败'})
        return Response({"code": 200, 'mes': '查询成功', 'data': ser.data})


class RolesView(APIView):
    def post(self, request):
        print('00000000000')
        data = request.data
        ser = RolesSer(data=data)
        print(data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, 'mes': '添加成功'})
        else:
            print(ser.errors)
            return Response({"code": 200, 'mes': ser.errors})

    def get(self, request):
        try:
            data = Roles.objects.all()
            ser = RolesSer(data, many=True)
        except Exception as e:
            print(e)
            return Response({"code": 200, 'mes': '获取失败'})
        return Response({"code": 200, 'mes': '查询成功', 'data': ser.data})


class AdminUserView(APIView):
    def post(self, request):
        data = request.data
        ser = AdminUserSer(data=data)
        print(data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, 'mes': '添加成功'})
        else:
            print(ser.errors)
            return Response({"code": 200, 'mes': ser.errors})

    def get(self, request):
        try:
            data = AdminUser.objects.all()
            ser = AdminUserSer(data, many=True)
        except Exception as e:
            print(e)
            return Response({"code": 200, 'mes': '获取失败'})
        return Response({"code": 200, 'mes': '查询成功', 'data': ser.data})


class RoleView(APIView):
    def get(self, request):
        # 获取前端传递的名称
        sname = request.GET.get('sname')
        # 获取前端传递的每页条数
        page_size = request.GET.get('page_size', 1)
        # 获取当前页数
        page = int(request.GET.get('page', 1))
        # 如果搜索条件为空，则查询所有数据
        roles = Roles.objects.filter(name=sname).all()
        if not roles:
            roles = Roles.objects.all()
            print(roles)
        # 实例化分页器，两个参数分别为 数据集(roles)，每页显示条数(page_size)
        pag = Paginator(roles, page_size)
        # 获取当前页的数据
        rdata = pag.page(page)
        # 序列化当前页的数据
        ser = RolesSer(rdata, many=True)
        return Response({"code": 200, 'total': pag.count, 'data': ser.data})


# 获取资源列表及此角色对应的所有资源
class RoleResourceView(APIView):
    def get(self, request):
        # 获取roleid
        roleid = request.GET.get('roleid')
        # 获取所有资源pid_id>0
        res = Resource.objects.filter(pid_id__gt=0).all()
        # 数组重组 key为id  label为name
        reslist = [{"key": i.id, "label": i.name} for i in res]
        # 获取角色
        role = Roles.objects.filter(id=roleid).first()
        # 获取角色对应的资源
        resource = role.resource.all()
        values = [i.id for i in resource]
        # 返回资源id列表
        return Response({"code": 200, 'reslist': reslist, 'values': values})

    def post(self, request):
        # 获取角色id
        roleid = request.data.get('roleid')
        # 获取选中的资源列表[1,2,3]
        values = request.data.get('values')

        # 根据id查询角色
        role = Roles.objects.filter(id=roleid).first()
        # 获取此角色继承的父类的资源列表
        res1 = list(role.resource.all())
        res2 = list(role.pid.resource.all())
        idlist = []
        # 获取到此角色配制的资源列表
        res = res1 + res2
        print(res,'-------',res1,'-----',res2)
        idlist = [i.id for i in res]
        # 查询互斥表
        mutually = MutuallyExclusiveModels.objects.filter(resource1__in=idlist).values('resource2')
        print('=============',mutually)
        # tlist = [i.resource2 for i in mutually]
        tlist = []
        for i in mutually:
            tlist.append(i['resource2'])
        print(tlist)
        # 将列表转换为集合
        set1 = set(idlist)
        print('===========',set1,'----------------')
        set2 = set(tlist)
        print('===========',set2,'============')
        # 取交集
        data = set1.intersection(set2)
        print('--------',data)
        if data :
            return Response({"code": 200, 'mes': '他们是互斥资源，添加失败'})

        # # 根据id查询角色
        # role = Roles.objects.filter(id=roleid).first()
        # 删除此角色对应的所有权限
        role.resource.clear()
        # 添加新的权限
        role.resource.add(*values)
        return Response({"code": 200, 'mes': '添加成功'})


r = redis.StrictRedis(host='localhost', port=6379, charset="utf-8", decode_responses=True, db=1)
class LoginView(APIView):
    def post(self, request):
        name = request.data.get('name')
        print(name)

        exp = datetime.utcnow() + timedelta(hours=8)

        payload = {
            'name': name,
            'exp': exp
        }

        users = AdminUser.objects.filter(name=name).first()
        # r.flushdb()
        # r.set('name1', 6)
        if users:
            token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
            # 用户对应的所有资源列表
            # userres = users.role.resource.all()
            userres1 = list(users.role.resource.all())
            userres2 = list(users.role.pid.resource.all())
            userres = userres1 + userres2
            print(userres2,'-----------',userres1,'--------',userres)

            # 定义返回的列表
            reslist = []
            # 把父级id存入，去重
            idslist = []
            # 接口权限列表
            interface = []
            for i in userres:
                # menulist.append(i.url)
                # 资源对应的接口权限
                interdata = i.interface.all()
                for inter in interdata:
                    interface.append(inter.url)
                # 获取所有资源的父类id
                pid = i.pid_id
                if pid not in idslist:
                    reslist.append({"id": pid, "name": i.pid.name, "son": []})
                    idslist.append(pid)

            # 遍历所有资源
            for j in userres:
                # 遍历菜单
                for index, s in enumerate(reslist):
                    # 当前资源属于哪个菜单，放到哪个菜单下
                    if j.pid_id == s['id']:
                        # 把资源id和资源名称存入
                        reslist[index]['son'].append({'id': j.id, 'name': j.name, 'url': j.url})
            # 获取接口权限
            interface_data = json.dumps(interface)
            print(interface_data)

            try:
                # r.set('name5', 2)
                # pass
                r.set('resourceinterface9', interface_data)
            except Exception as e:
                print(e)
                return Response({"code": 200, 'mes': '存储失败'})
            return Response({"code": 200, 'mes': '登录成功', 'token': token, 'menulist': reslist,'permmison': interface})
        else:
            return Response({"code": 200, 'mes': '登录失败'})
